package com.moli.lumpSugar.websocket.service.impl;

import com.auth0.jwt.interfaces.Claim;

import com.moli.lumpSugar.common.constant.RedisKey;
import com.moli.lumpSugar.common.utils.JwtUtils;
import com.moli.lumpSugar.common.utils.RedisUtils;
import com.moli.lumpSugar.websocket.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @program: LumpSugarChat
 * @description:
 * @author: zhangjt
 * @create: 2024-10-23 10:28
 **/
@Service
public class LoginServiceImpl implements LoginService {
    public static final int TOKEN_EXPIRE_DAY = 3;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private ThreadPoolTaskExecutor lumpSugarChatExecutor;

    @Override
    public boolean verify(String token) {
        Map<String, Claim> stringClaimMap = jwtUtils.verifyToken(token);
        return stringClaimMap != null && !stringClaimMap.isEmpty();
    }

    @Override
    public void renewalTokenIfNecessary(String token) {
        lumpSugarChatExecutor.execute(()->{
            Long validUid = getValidUid(token);
            if (Objects.isNull(validUid)) {
                return;
            }
            Long expire = RedisUtils.getExpire(getUserTokenKey(validUid), TimeUnit.DAYS);
            if (expire == -2) {
                return;
            }
            if (expire < 1) {
                RedisUtils.expire(getUserTokenKey(validUid), TOKEN_EXPIRE_DAY, TimeUnit.DAYS);
            }
        });
    }

    @Override
    public String login(Long uid) {
        // 生成用户对应的token
        String token = jwtUtils.createToken(uid);
        RedisUtils.set(getUserTokenKey(uid), token, TOKEN_EXPIRE_DAY, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Long getValidUid(String token) {
        Long uidOrNull = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uidOrNull)) {
            return null;
        }
        String oldToken = RedisUtils.getStr(getUserTokenKey(uidOrNull));
        return Objects.equals(oldToken, token) ? uidOrNull : null;
    }

    private String getUserTokenKey(Long uid) {
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
    }
}
